<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit"
                 size="small" v-if="sys_role_add">添加
      </el-button>
    </div>
    <el-table :key='tableKey' :data="list" size="small" v-loading="listLoading" element-loading-text="加载中..." border fit
              highlight-current-row style="width: 99%">
      <el-table-column align="center" label="序号">
        <template slot-scope="scope">
          <span>{{scope.row.roleId}}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="编号">
        <template slot-scope="scope">
          <span>{{scope.row.code}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="描述">
        <template slot-scope="scope">
          <span>{{scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createDate | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="status-col" label="状态">
        <template slot-scope="scope">
          <span>{{scope.row.enable | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="400" v-if="sys_role_edit">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="small" type="primary" @click="handlePermission(scope.row)">操作权限</el-button>
          <el-button size="small" type="primary" @click="handlePermitRole(scope.row)">授予权限</el-button>
          <el-button v-if="scope.row.enable" size="small" type="danger" @click="toggle(scope.row, false)">停用</el-button>
          <el-button v-if="!scope.row.enable" size="small" type="success" @click="toggle(scope.row, true)">启用
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,30,50,100]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="序号" prop="roleId" v-if="dialogStatus == 'update'">
          <el-input v-model="form.roleId" placeholder="序号" :disabled=true></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="code">
          <el-input v-model="form.code" placeholder="编号"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="描述"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="enable">
          <el-select class="filter-item" v-model="form.enable" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item" :label="item | statusFilter" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus == 'create'" type="primary" @click="create('form')">保存</el-button>
        <el-button v-else type="primary" @click="update('form')">更新</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogPermitRoleVisible">
      <el-tree class="filter-tree" :data="roleData" :default-checked-keys="checkedKeys" check-strictly node-key="roleId"
               highlight-current show-checkbox ref="permitRoleDialog" :props="defaultProps"
               :filter-node-method="filterNode" default-expand-all>
      </el-tree>
      <div slot="footer" class="dialog-footer" v-if="roleData.length>0">
        <el-button type="primary" @click="updatePermitRole(roleId)">更 新</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogPermissionVisible">
      <el-tree class="filter-tree" :data="permissionData" :default-checked-keys="checkedKeys" check-strictly
               node-key="permissionId" highlight-current :props="defaultProps" show-checkbox ref="permissionDialog"
               :filter-node-method="filterNode"
               default-expand-all>
      </el-tree>
      <div slot="footer" class="dialog-footer" v-if="permissionData.length>0">
        <el-button type="primary" @click="updatePermission(roleId)">更 新</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchList,
    getObj,
    addObj,
    putObj,
    toggleObj,
    permitRoleUpdate,
    permissionUpdate,
    fetchPermitRole,
    fetchPermission,
    fetchAllPermitRole,
    fetchAllPermission
  } from "@/api/role";
  import {mapGetters} from "vuex";
  import waves from "@/directive/waves/index.js"; // 水波纹指令

  export default {
    name: "table_role",
    directives: {
      waves
    },
    data() {
      return {
        roleData: [],
        permissionData: [],
        checkedKeys: [],
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20
        },
        form: {
          name: undefined,
          code: undefined,
          description: undefined,
          roleId: undefined,
          enable: undefined
        },
        rules: {
          name: [
            {
              required: true,
              message: "名称",
              trigger: "blur"
            },
            {
              min: 3,
              max: 20,
              message: "长度在 3 到 20 个字符",
              trigger: "blur"
            }
          ],
          code: [
            {
              required: true,
              message: "编号",
              trigger: "blur"
            },
            {
              min: 3,
              max: 20,
              message: "长度在 3 到 20 个字符",
              trigger: "blur"
            }
          ],
          description: [
            {
              required: true,
              message: "描述",
              trigger: "blur"
            },
            {
              min: 3,
              max: 20,
              message: "长度在 1 到 100 个字符",
              trigger: "blur"
            }
          ]
        },
        statusOptions: [true, false],
        rolesOptions: undefined,
        dialogFormVisible: false,
        dialogPermissionVisible: false,
        dialogPermitRoleVisible: false,
        dialogStatus: "",
        textMap: {
          update: "编辑",
          create: "创建",
          permission: "分配权限",
          permitRole: "分配授权角色"
        },
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        tableKey: 0,
        sys_role_add: false,
        sys_role_edit: false
      };
    },
    filters: {
      statusFilter(type) {
        const statusMap = {
          true: '启用',
          false: '停用'
        }
        return statusMap[type]
      }
    },
    created() {
      this.getList();
      this.sys_role_add = this.permissions["sys_role_add"];
      this.sys_role_edit = this.permissions["sys_role_edit"];
    },
    computed: {
      ...mapGetters(["elements", "permissions"])
    },
    methods: {
      getList() {
        this.listLoading = true;
        fetchList(this.listQuery).then(response => {
          this.list = response.data.data.content;
          this.total = response.data.data.total;
          this.listLoading = false;
        });
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handleCreate() {
        this.resetTemp();
        this.dialogStatus = "create";
        this.dialogFormVisible = true;
      },
      handleUpdate(row) {
        getObj(row.roleId).then(response => {
          this.form = response.data.data;
          this.dialogFormVisible = true;
          this.dialogStatus = "update";
        });
      },
      handlePermission(row) {
        fetchPermission(row.roleId).then(response => {
          this.checkedKeys = response.data.data.map(function (m) {
            return m.permissionId
          });
          fetchAllPermission().then(response => {
            this.permissionData = response.data.data.content;
            this.dialogStatus = "permission";
            this.dialogPermissionVisible = true;
            this.roleId = row.roleId;
          });
        })
      },
      handlePermitRole(row) {
        fetchPermitRole(row.roleId).then(response => {
          this.checkedKeys = response.data.data.map(function (m) {
            return m.roleId
          });
          fetchList({page: 1, limit: 999}).then(response => {
            this.roleData = response.data.data.content;
            this.dialogStatus = "permitRole";
            this.dialogPermitRoleVisible = true;
            this.roleId = row.roleId;
          });
        })
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      getNodeData(data) {
        console.log(data);
      },
      toggle(row, enable) {
        toggleObj(row.roleId, enable).then(response => {
          this.dialogFormVisible = false;
          this.getList();
          this.$notify({
            title: "成功",
            message: "切换成功",
            type: "success",
            duration: 2000
          });
        });
      },
      create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            addObj(this.form).then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: "成功",
                message: "创建成功",
                type: "success",
                duration: 2000
              });
            });
          } else {
            return false;
          }
        });
      },
      cancel(formName) {
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();
      },
      update(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            this.dialogFormVisible = false;
            putObj(this.form).then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: "成功",
                message: "修改成功",
                type: "success",
                duration: 2000
              });
            });
          } else {
            return false;
          }
        });
      },
      updatePermission(roleId) {
        permissionUpdate(roleId, this.$refs.permissionDialog.getCheckedKeys()).then(() => {
          this.dialogPermissionVisible = false
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
        });
      },
      updatePermitRole(roleId) {
        permitRoleUpdate(roleId, this.$refs.permitRoleDialog.getCheckedKeys()).then(() => {
          this.dialogPermitRoleVisible = false
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
        });
      },
      resetTemp() {
        this.form = {
          roleId: undefined,
          name: undefined,
          code: undefined,
          description: undefined,
          enable: true
        };
      }
    }
  };
</script>
